<template>
  <div class="comboPlanPrint">
    <!-- 打印 -->
    <el-dialog v-model="openCodeCard" append-to-body :show-close="false" width="50%">
      <div class="show-box">
        <div id="printCodeBox" style="page-break-after: always">
          <div class="pageCodeDiv">
            <div class="title-box"> 餐品信息</div>
            <div class="info-box">
              <el-descriptions title="" :column="2">
                <el-descriptions-item label="计划名称：">{{
                  comboPlanData.cplanName
                }}</el-descriptions-item>
                <el-descriptions-item label="投放设备：">{{
                  comboPlanData.machineName
                }}</el-descriptions-item>
                <el-descriptions-item label="投放开始时间：">{{
                  formatDate1(comboPlanData.startTime)
                }}</el-descriptions-item>
                <el-descriptions-item label="投放结束时间：">{{
                  formatDate1(comboPlanData.endTime)
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="title-box">投放货道餐品信息</div>
            <div class="info-box">
              <div>
                <label>{{ weekDayPrint }}</label>
                <div class="combo-box">
                  <div
                    class="combo-box-item"
                    :class="{ isFourth: comboPlanData.machineType == 2 }"
                    :style="{ 'margin-top': comboPlanData.machineType == 2 ? '12px' : '0px' }"
                    v-for="(itemRow, indexRow) in comboPlanByDayShow"
                    :key="indexRow"
                  >
                    <div class="item-title-box"> 货道号：{{ itemRow.roadNumber }} </div>
                    <div>
                      <el-input v-model="itemRow.showText" readonly />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="title-box">餐品信息统计</div>
            <div class="info-box">
              <el-descriptions title="" :column="4">
                <el-descriptions-item v-for="(item, index) in comboStatistics" :key="index"
                  >{{ item.comboName + ' * ' + item.comboNum }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openCodeCard = false">关 闭</el-button>
          <el-button type="primary" v-print="print">打 印</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 日期选择 -->
    <el-dialog v-model="DialogVisible" title="请选择打印日期" width="45%" align-center>
      <div class="date-box">
        <el-radio-group v-model="weekDayPrint">
          <el-radio-button :label="item.date" v-for="(item, index) in comboRoadShow" :key="index">
            <template #default>
              <div>{{ item.weekday }}</div>
              <div>{{ item.date }}</div>
            </template>
          </el-radio-button>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="DialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePrintBySelectedDay">预览</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="comboPlanPrint">
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate, formatDate1 } from '@/utils/index'
import { getComboMachineInfo, getComboRoadInfo } from '@/api/devote'
const { proxy } = getCurrentInstance()

const DialogVisible = ref(false) //日期选择框
const openCodeCard = ref(false) //餐品计划框
const comboPlanData = ref(null)

const roadList = ref(null)
function getComboPlanList(cplanId) {
  getComboMachineInfo(cplanId).then((res) => {
    let nameArr = res?.data.map((ele) => (ele.deviceName ? ele.deviceName : ele.machineId))
    comboPlanData.value.machineName = nameArr.join(',')
  })
  getComboRoadInfo(cplanId).then((res) => {
    roadList.value = res?.data ?? []
    comboRoadConversion(roadList.value)
  })
  DialogVisible.value = true
}

const comboRoadShow = ref(null)
const weekDayPrint = ref(null)
function comboRoadConversion(receiveData) {
  //根据日期生成二维数组
  const outerRingArr = []
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

  for (const ele of receiveData) {
    const existingData = outerRingArr.find(
      (item) => formatDate1(item.date) === formatDate1(ele.date)
    )
    if (existingData) {
      existingData.comboRad.push({
        roadNumber: ele.roadNumber,
        comboId: ele.comboId,
        comboName: ele.comboName,
        comboNum: ele.comboNum,
        cplanId: ele.cplanId,
        showText:
          comboPlanData.value.machineType == 2 ? ele.comboName : ele.comboName + '*' + ele.comboNum
      })
    } else {
      outerRingArr.push({
        date: formatDate1(ele.date),
        comboRad: [
          {
            roadNumber: ele.roadNumber,
            comboId: ele.comboId,
            comboName: ele.comboName,
            comboNum: ele.comboNum,
            cplanId: ele.cplanId,
            showText:
              comboPlanData.value.machineType == 2
                ? ele.comboName
                : ele.comboName + '*' + ele.comboNum
          }
        ]
      })
    }
  }
  //日期设置星期
  outerRingArr.forEach((element) => {
    const date = new Date(element.date)
    element.weekday = weekdays[date.getDay()]
  })
  comboRoadShow.value = outerRingArr
}

//** 日期选择确定 */
const comboPlanByDayShow = ref(null)
const comboStatistics = ref(null)
function handlePrintBySelectedDay() {
  if (!weekDayPrint.value) {
    ElMessage.error('请选择打印日期')
    return
  }
  let currDateArr = comboRoadShow.value.filter((item) => item.date == weekDayPrint.value)[0]
    .comboRad
  let arr = []
  let len = comboPlanData.value.machineType == 2 ? 60 : 24
  for (let j = 0; j < len; j++) {
    let roadNumber =
      comboPlanData.value.machineType == 2
        ? Math.ceil((j + 1) / 4) + '' + ((j + 1) % 4 === 0 ? 4 : (j + 1) % 4)
        : Math.ceil((j + 1) / 3) + '' + ((j + 1) % 3 === 0 ? 3 : (j + 1) % 3)
    let obj = {
      roadNumber: roadNumber,
      comboNum: null,
      comboId: null,
      date: weekDayPrint.value,
      comboName: '',
      showText: ''
    }
    let _index = currDateArr.findIndex((ele) => ele.roadNumber === roadNumber)
    if (_index > -1) {
      obj = currDateArr[_index]
    }
    arr.push(obj)
  }
  comboPlanByDayShow.value = arr

  //餐品统计
  const resultMap = {}
  let arr1 = comboRoadShow.value.filter((item) => item.date == weekDayPrint.value)
  arr1.forEach((item) => {
    item.comboRad.forEach((obj) => {
      const comboId = obj.comboId
      const comboNum = Number(obj.comboNum)

      if (comboId in resultMap) {
        resultMap[comboId].comboNum = Number(resultMap[comboId].comboNum) + comboNum
      } else {
        resultMap[comboId] = obj
      }
    })
  })
  comboStatistics.value = Object.values(resultMap)

  if (arr1.length > 0) {
    openCodeCard.value = true
    DialogVisible.value = false
  }
}

function handlePrint(data) {
  comboPlanData.value = data
  weekDayPrint.value = null
  comboStatistics.value = []
  getComboPlanList(data.cplanId)
}

const print = {
  id: 'printCodeBox',
  popTitle: '&nbsp;',
  extraHead: '',
  preview: false, // 是否启动预览模式，默认是false
  zIndex: 20002, // 预览窗口的z-index
  closeCallback() {
    openCodeCard.value = false
  }
}

defineExpose({
  handlePrint
})
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 0;
}
:deep(.el-radio-button .el-radio-button__inner) {
  white-space: normal;
  line-height: 1.2;
}
.show-box {
  max-height: 600px;
  overflow-y: auto;
}

.date-box {
  width: 100%;
  height: 150px;
  display: flex;
  justify-content: center;
}
.pageCodeDiv {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  font-size: 13px;
  margin-bottom: 30px;
  .title-box {
    width: 100%;
    color: var(--el-text-color-primary);
    font-size: 16px;
    font-weight: 700;
    padding-left: 5px;
    border-left: 4px solid #2f51ff;
    margin-bottom: 20px;
  }
  .info-box {
    width: 100%;
    min-height: 100px;
    padding-left: 10px;
    .combo-box {
      width: 100%;
      padding-top: 10px;
      height: auto;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      .combo-box-item {
        width: 30%;
        margin-bottom: 15px;
        border: 1px solid #dedede;
        border-radius: 6px;
        padding: 8px;
        margin-left: 15px;
        .item-title-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 20px;
        }
        &:nth-child(3n + 1) {
          margin-left: 0px;
        }
      }
      .isFourth {
        width: 22%;
        &:nth-child(3n + 1) {
          margin-left: 15px;
        }
        &:nth-child(4n + 1) {
          margin-left: 0px;
        }
      }
    }
  }
}

@media print {
  @page {
    size: auto;
  }
  body,
  html {
    height: auto !important;
    font-family: Arial, sans-serif;
    text-align: center;
    vertical-align: middle;
    display: table-cell;
  }
  .pageCodeDiv {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    font-size: 13px;
  }
}
</style>
